<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<link rel="stylesheet" type="text/css" media="screen" href="/css/bootstrap.min.css">
	<link rel="stylesheet" type="text/css" media="screen" href="/css/dataTables.bootstrap.min.css">
	<link rel="stylesheet" type="text/css" media="screen" href="/layui/css/layui.css">
	<link rel="stylesheet" href="/css/treetable/jquery.treetable.css"/>
	<link rel="stylesheet" href="/css/treetable/jquery.treetable.theme.default.css"/>
	<link rel="stylesheet" type="text/css" href="/css/bootstrap-select.min.css">
	<link rel="stylesheet" type="text/css" href="/at-js/css/jquery.atwho.css">
	<script src="/js/libs/jquery-2.1.1.min.js"></script>
	<script src="/js/bootstrap/bootstrap.min.js"></script>
	<script src="/js/bootstrap/bootstrap-select.min.js"></script>
	<script src="/js/jq.js"></script>
	<script src="/js/plugin/bootstrapvalidator/bootstrapValidator.min.js"></script>
	<script src="/js/common.js"></script>
	<script src="/layui/layui.js"></script>
	<script src="/js/dict.js"></script>
	<script src="/js/libs/jquery.ztree.all-3.5.min.js"></script>
	<script src="/js/my/ztree-menu.js"></script>
	<script src="/js/my/permission.js"></script>
	<script src="/js/plugin/datatables/jquery.dataTables.min.js"></script>
	<script src="/js/plugin/datatables/dataTables.bootstrap.min.js"></script>
	<script src="/js/libs/jquery.treetable.js"></script>
	<script src="/js/plugin/jquery-caret/jquery.caret.js"></script>
	<script src="/at-js/js/jquery.atwho.js"></script>
</head>
<body>
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 col-md-offset-2 col-lg-offset-2">
	<form class="form-horizontal" onsubmit="return false" id="form">
		<fieldset>
			<input type="hidden" id="projectId" name="projectId">
			<div class='form-group'>
				<label class='col-md-4 control-label'>任务名称</label>
				<div class='col-md-8'>
					<input class='form-control' placeholder='任务名称' type='text' name='name' id='name'
						   data-bv-notempty='true' data-bv-notempty-message='任务名称 不能为空'>
				</div>
			</div>

			<div class='form-group'>
				<label class='col-md-4 control-label'>执行者：</label>
				<div class='col-md-8'>
					<input class='form-control' type='hidden' name='participantId' id='participantId'
						   data-bv-notempty='true' data-bv-notempty-message='执行者 不能为空'>
					<input style="width: 90%;float: left;" class='form-control' placeholder='执行者' type='text'
						   name='participantName' id='participantName' data-bv-notempty='true'
						   data-bv-notempty-message='执行者 不能为空'
						   readonly>
					<button style="width: 10%;float: right; height: 32px; line-height: 32px;"
							class="layui-btn layui-btn-sm"
							onclick="projectList()">
						<i class="layui-icon">&#xe615;</i>
					</button>
				</div>
			</div>
			<div class='form-group'>
				<label class='col-md-4 control-label'>预计工时：</label>
				<div class='col-md-8'>
					<input class="form-control" placeholder="预计工时" name="estimateWorkingHours" id="estimateWorkingHours"
						   data-bv-notempty='true' data-bv-notempty-message='预计工时 不能为空'>
				</div>
			</div>
			<div class='form-group'>
				<label class='col-md-4 control-label'>任务描述：</label>
				<div class='col-md-8'>
					<div class="panel panel-default" name="description" id="description" contenteditable="true"
						 style="width: 100%; min-height: 100px;"></div>
				</div>
			</div>
			<div class='form-group'>
				<label class='col-md-4 control-label'>截止日期</label>
				<div class='col-md-8'>
					<input class='form-control' placeholder='截止日期' type='text' name='deadline' id='deadline'
						   data-bv-notempty='true' data-bv-notempty-message='截止日期 不能为空'>
				</div>
			</div>
			<div class='form-group'>
				<label class='col-md-4 control-label'>优先级:</label>
				<div class='col-md-8'>
					<select class="form-control input-sm selectpicker show-tick" name="grade" id="grade"
							title="任务状态" data-live-search="true"></select>
				</div>
			</div>
			<div class='form-group'>
				<label class='col-md-4 control-label'>附件</label>
				<div class="layui-upload col-md-8">
					<button type="button" class="layui-btn layui-btn-normal layui-btn-sm" id="selectScreenshotPath">
						选择多文件
					</button>
					<input type="hidden" value="" id="screenshotPath" name="screenshotPath">
					<button type="button" class="layui-btn layui-btn-sm" id="uploadScreenshotPath">开始上传</button>
					<div class="layui-upload-list">
						<table class="layui-table" style="table-layout:fixed;">
							<thead>
							<tr>
								<th>文件名</th>
								<th>大小</th>
								<th>状态</th>
								<th>操作</th>
							</tr>
							</thead>
							<tbody id="screenshotPathList"></tbody>
						</table>
					</div>
				</div>
			</div>

			<div class="form-actions">
				<div class="row" align="center">
					<div class="col-md-12">
						<button class="btn btn-primary" type="submit" onclick="save()">
							<i class="fa fa-save"></i> 保存
						</button>
					</div>
				</div>
			</div>
		</fieldset>
	</form>
</div>

	<script type="text/javascript">
	    $(function () {
            $('#form').bootstrapValidator();
            runAt();
        });

        layui.use(['layer', 'laydate', 'upload'], function () {
            var layer = layui.layer;
            var laydate = layui.laydate;
            var upload = layui.upload;

            laydate.render({
                elem: '#deadline',
                done: function (value, date, endDate) {
                    // console.log(value); //得到日期生成的值，如：2017-08-18
                    // console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
                    // console.log(endDate); //得结束的日期时间对象，开启范围选择（range: true）才会返回。对象成员同上。
                    if ($("#form").data('bootstrapValidator')) {
                        $("#form").data('bootstrapValidator').resetForm();
                    }
                }
            });

            var screenshotPathListView = $('#screenshotPathList');
            var uploadListIns = upload.render({
                elem: '#selectScreenshotPath'
                , url: '/files'
                , accept: 'file'
                , multiple: true
                , auto: false
                , bindAction: '#uploadScreenshotPath'
                , choose: function (obj) {
                    var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                    //读取本地文件
                    obj.preview(function (index, file, result) {
                        var tr = $(['<tr id="upload-' + index + '">'
                            , '<td style ="white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">' + file.name + '</td>'
                            , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                            , '<td>等待上传</td>'
                            , '<td>'
                            , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                            , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                            , '</td>'
                            , '</tr>'].join(''));

                        //单个重传
                        tr.find('.demo-reload').on('click', function () {
                            obj.upload(index, file);
                        });

                        //删除
                        tr.find('.demo-delete').on('click', function () {
                            delete files[index]; //删除对应的文件
                            tr.remove();
                            // 重新获得所有上传文件
                            $('#screenshotPath').val('');
                            $('.screenshotPathFile').each(function () {
                                $('#screenshotPath').val($('#screenshotPath').val() + '|' + $(this).data('id'));
                            });
                            uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                        });

                        screenshotPathListView.append(tr);
                    });
                }
                , done: function (res, index, upload) {
                    if (res.code === 0) { //上传成功
                        var tr = screenshotPathListView.find('tr#upload-' + index)
                            , tds = tr.children();
                        tds.eq(0).html('<a target="_blank" data-id="' + res.data.id + '" class="screenshotPathFile" href="/files' + res.data.url + '">' + res.data.fileName + '</a>');
                        tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                        // tds.eq(3).html(''); //清空操作

                        // 追加文件id
                        $('#screenshotPath').val($('#screenshotPath').val() + '|' + res.data.id);
                        return delete this.files[index]; //删除文件队列已经上传成功的文件
                    }
                    this.error(index, upload);
                }
                , error: function (index, upload) {
                    var tr = screenshotPathListView.find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
                    tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
                }
            });
        });
        var pers = checkPermission();

        var status = showDictSelect('status', 'task_status', '', '0');
        var grade = showDictSelect('grade', 'dept_level', '', '1');

        function projectList(){
            var projectId = $("#projectId").val();
            let path = '/pages/user/userTableForTms.html?isAll=true&isMultiSelect=false&projectId=' + projectId;
            var flushFields = ['participantId:id', 'participantName:nickname'];
            let echo = []; //传输的数组
            let count = 0; //传输的数组长度
            let val = $('#' + flushFields[0].split(':')[0]).val().trim();
            if (val) {
                count = val.split(';').length;
            }

            for (let i = 0; i < count; i++) {
                let item = {};
                $.each(flushFields, function (j, field) {
                    let formField = field.split(':')[0];
                    let entityField = field.split(':')[1];
                    item[entityField] = $('#' + formField).val().split(';')[i];
                });
                echo[i] = item;
            }

            path += '&echo=' + encodeURIComponent(JSON.stringify(echo));

            layer.open({
                type: 2,
                title: '任务成员列表',
                shadeClose: true, //是否点击阴影关闭层
                area: ['800px', '400px'],
                offset: 'auto', //rb右下角弹出
                anim: 0,
                content: [path, 'yes'], //iframe的url，no代表不显示滚动条
                fixed: true, // 是否固定
                maxmin: true,
                btn: ['确定', '清除', '取消'],
                yes: function (index, layero) {
                    let rows = layero.find("iframe")[0].contentWindow.example.rows('.success').data();
                    if (flushFields) {
                        $.each(rows, function (rowIndex, row) {
                            $.each(flushFields, function (fieldIndex, item) {
                                let fieldsPair = item.split(':');
                                if (rowIndex === 0) {
                                    $('#' + fieldsPair[0].trim()).val(row[fieldsPair[1].trim()]);
                                } else {
                                    $('#' + fieldsPair[0].trim()).val($('#' + fieldsPair[0].trim()).val().trim() + ';' + row[fieldsPair[1].trim()]);
                                }
                            });
                        });
                        updateField('/task/updateParticipant', 'participantId:' + $("#participantId").val());
                    }

                    if ($("#form").data('bootstrapValidator')) {
                        $("#form").data('bootstrapValidator').resetForm();
                    }
                    layer.close(index); //如果设定了yes回调，需进行手工关闭
                },
                cancel: function (index, layero) {
                    if ($("#form").data('bootstrapValidator')) {
                        $("#form").data('bootstrapValidator').resetForm();
                    }
                },
                btn2: function (index, layero) {
                    if (flushFields) {
                        $.each(flushFields, function (index, item) {
                            $('#' + item.split(':')[0]).val('');
                        });
                    }
                    if ($("#form").data('bootstrapValidator')) {
                        $("#form").data('bootstrapValidator').resetForm();
                    }
                }
            });
        }
		initData();
        function initData() {
            var id = getUrlParam("taskId");
            if (id) {
                $.ajax({
                    type: 'get',
                    url: '/task/' + id,
                    async: false,
                    success: function (json) {
                        if (json.code === 0) {
                            var data = json.data;
                            $('#name').val(data.name);
                            $('#projectId').val(data.projectId);
                            $('#participantId').val(data.participantId);
                            $('#participantName').val(data.participantName);
                            $('#estimateWorkingHours').val(data.estimateWorkingHours);
                            $('#description').html(data.description);
                            $('#deadline').val(data.deadline);
                            $('#grade').val(data.grade);
                            $('#screenshotPath').val(data.screenshotPath);
                            var screenshotPaths = data.screenshotPaths;
                            $('#screenshotPathList').empty();
                            if (screenshotPaths) {
                                $.each(screenshotPaths, function (index, file) {
                                    var tr = $(['<tr id="upload-' + index + '">'
                                        , '<td style ="white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">'
                                        , '<a target="_blank" data-id="' + file.id + '" class="screenshotPathFile" href="/files' + file.url + '">' + file.fileName + '</a>'
                                        , '</td>'
                                        , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                                        , '<td>已上传</td>'
                                        , '<td>'
                                        , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                                        , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                                        , '</td>'
                                        , '</tr>'].join(''));

                                    //单个重传
                                    tr.find('.demo-reload').on('click', function () {
                                        obj.upload(index, file);
                                    });

                                    //删除
                                    tr.find('.demo-delete').on('click', function () {
                                        // delete files[index]; //删除对应的文件
                                        tr.remove();
                                        // 重新获得所有上传文件
                                        $('#screenshotPath').val('');
                                        $('.screenshotPathFile').each(function () {
                                            $('#screenshotPath').val($('#screenshotPath').val() + '|' + $(this).data('id'));
                                        });
                                    });

                                    $('#screenshotPathList').append(tr);
                                });
                            }
                        }
                    }
                });
            }
        }

        function runAt() {
            var users = [];
			var id = $("#projectId").val();
            $.ajax({
                type: 'get',
                url: '/users/partList/' + id,
                async: false,
                success: function (json) {
                    if (json.code === 0) {
                        users = json.data;
                    }
                }
            });

            let offset = top.getIFrameOffset();

            offset.top -= 65;

            var at_config = {
                at: "@",
                data: users,
                searchKey: 'nickname',
                headerTpl: '<div class="atwho-header">User List<small>↑&nbsp;↓&nbsp;</small></div>',
                insertTpl: '<span data-id="${id}" name="atUsers">@${nickname}</span>',
                displayTpl: "<li>${nickname} <small>${username}</small></li>",
                limit: 5,
                offset: offset
            };

            var $inputor = $('#description').atwho(at_config);
        }

        function save() {
            $('#form').bootstrapValidator();
            var bootstrapValidator = $("#form").data('bootstrapValidator');
            bootstrapValidator.validate();
            if (!bootstrapValidator.isValid()) {
                return;
            }

            var formdata = $("#form").serializeObject();
            formdata.description = $('#description').html();
            formdata.atUsers = [];

            $.each($('#form').find('[name=atUsers]'), function (index, item) {
                formdata.atUsers[index] = $(item).data("id");
            });

            $.ajax({
                type: 'post',
                url: '/task/',
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(formdata),
                success: function (data) {
                    layer.msg("复制成功", {shift: -1, time: 1000}, function () {
                        parent.location.reload();
                    });
                }
            });
        }
		
	</script>
</body>
</html>
